/**
 * 报销单封装
 * @author hongwei 2018-09-10
 */
(function (window) {
    'use strict';
    var expenseAdd = function(params) {
        $.extend(this.params, params);
        var that = this;
        that._init();   //初始化操作
    };

    var toast = new auiToast();

    expenseAdd.prototype = {

        params : {
            data1  : []      //报销单人员数据
            ,data2 : []      //申请单人员数据
            ,ids : []
        }
        ,_init : function () {
            var that = this;
            that.getExpenseInfo();          //step1:获取出差报销单数据
            that.getPassengerList();        //step2:获取出差/审核人员接口,包含step5
            that.approvePicker();           //step7:审核人 选择器
            that.delTravelPersonAddEvent(); //step8:删除人员
            that.addOrderChooseIds();       //step10:发送监听事件,包含step4
            that.startEndDateClick();       //step11:开始日期和结束日期点击
            that.addExpendseClick();        //step12:添加报销单明细
            that.submitData();              //step15:提交出差申请单,包含step16
            that.uploadImg();               //step17:上传图片
            that.showOrder();               //step18:显示订单
            that.imageDelete();             //step19:图片删除操作

        }


        //step1:获取出差报销单数据
        , getExpenseInfo : function() {
            var that = this;

            var param = {};
            param.url = Config.common.getCompanyInfo;
            //请求申请单列表接口
            ajax(param, function(ret) {
                if (ret.apply_order === 1) {
                    that.getApplyList();        //step3-1:获取出差申请单列表,包含step6,step9
                } else {
                    that.travelOrderChoose();   //step3-2:打开选择订单列表
                }
            })
        }


        //step2:获取出差/审核人员接口
        ,getPassengerList :function () {
            var that = this;

            var param = {};
            param.url = Config.travel.getPassengerList;
            //请求申请单列表接口
            ajax(param, function(ret) {
                if (ret.code === 1) {
                    //审批人中删除当前登录人
                    delete ret.data[$api.getStorage('user_id')];
                    that.createList(ret.data, that.params.data1);
                } else {
                    toast.custom({
                        title: "获取审批人失败",
                        html: '<i class="aui-iconfont aui-icon-info"></i>',
                        duration: 2000
                    });
                }
            })
        }

        //step3-1:获取出差申请单列表
        ,getApplyList : function () {
            var that = this;

            var param = {};
            param.url = Config.travel.mineApplyList;
            param.data = {};
            //请求申请单列表接口
            ajax(param, function(ret) {
                if (ret.code === 1) {
                    that.createList2(ret.data.data, that.params.data2);
                    that.initPickerApply();
                } else {
                    toast.custom({
                        title: ret.msg,
                        html: '<i class="aui-iconfont aui-icon-info"></i>',
                        duration: 2000
                    });
                }
            });
            $("#picker2").children('.aui-list-item-title').text('请选择出差申请单');
        }


        //step3-2:打开选择订单列表
        ,travelOrderChoose : function () {
            //申请单未开启
            $("#picker2").click(function() {
                api.openWin({
                    name: 'travel_order_choose_win',
                    url: './travel_order_choose_win.html'
                });
            });
            $("#picker2").children('.aui-list-item-title').text('请选择差旅订单');
        }


        //step4:获取订单列表
        ,getOrderList : function (type, ids) {
            var that = this;

            var param = {};
            param.url = Config.travel.getApplyOrderList;
            param.data = {
                type: type,
                ids: ids,
                limit: 20
            };
            // console.log(param);
            //请求申请单列表接口
            ajax(param, function(ret) {
                if (ret.code === 1) {
                    if (ret.data.plane.total > 0 || ret.data.hotel.total > 0 || ret.data.train.total > 0) {
                        var interText = doT.template($("#order_tpl").text());
                        //清空
                        $("#order_list").text('');
                        //机票
                        if (ret.data.plane.total > 0) {
                            var htmlPlane = '<div class="aui-info aui-margin-t-10 aui-padded-l-10 aui-padded-r-10" style="border-bottom: 1px solid #dddddd;margin:0;">';
                            htmlPlane += '<div class="aui-info-item"><span class="aui-margin-l-5">机票订单</span></div>';
                            htmlPlane += '<div class="aui-info-item"><span class="aui-margin-r-5 show_order" data-group="plane">展开</span></div></div>';
                            $("#order_list").append(htmlPlane);
                            $("#order_list").append(interText(ret.data.plane.data));
                        }
                        //酒店
                        if (ret.data.hotel.total > 0) {
                            var htmlHotel = '<div class="aui-info aui-margin-t-10 aui-padded-l-10 aui-padded-r-10" style="border-bottom: 1px solid #dddddd;margin:0;">';
                            htmlHotel += '<div class="aui-info-item"><span class="aui-margin-l-5">酒店订单</span></div>';
                            htmlHotel += '<div class="aui-info-item"><span class="aui-margin-r-5 show_order" data-group="plane">展开</span></div></div>';
                            $("#order_list").append(htmlHotel);
                            $("#order_list").append(interText(ret.data.hotel.data));
                        }
                        //车票
                        if (ret.data.train.total > 0) {
                            var htmlTrain = '<div class="aui-info aui-margin-t-10 aui-padded-l-10 aui-padded-r-10" style="border-bottom: 1px solid #dddddd;margin:0;">';
                            htmlTrain += '<div class="aui-info-item"><span class="aui-margin-l-5">车票订单</span></div>';
                            htmlTrain += '<div class="aui-info-item"><span class="aui-margin-r-5 show_order" data-group="plane">展开</span></div></div>';
                            $("#order_list").append(htmlTrain);
                            $("#order_list").append(interText(ret.data.train.data));
                        }

                        //统计日期
                        that.calculateDate();
                    } else {
                        toast.custom({
                            title: "您的申请单没有相关行程或行程未开始",
                            html: '<i class="aui-iconfont aui-icon-info"></i>',
                            duration: 2000
                        });
                    }
                } else {
                    toast.custom({
                        title: "获取订单失败",
                        html: '<i class="aui-iconfont aui-icon-info"></i>',
                        duration: 2000
                    });
                }
            })
        }

        //step5:picker 底部选择器数据结构生成
        ,createList :function (obj, list) {
            var arr = Object.keys(obj);
            for (var i = 0; i < arr.length; i++) {
                var k = arr[i];
                var temp = [];
                temp.text = obj[k].user_name;
                temp.value = obj[k].user_id;
                list.push(temp);
            }
        }

        //step6:picker 底部选择器数据结构生成2
        ,createList2 : function (obj, list) {
            var that = this;

            var arr = Object.keys(obj);
            for (var i = 0; i < arr.length; i++) {
                var k = arr[i];
                var temp = [];
                temp.text = obj[k].travel_application_number;
                temp.value = obj[k].id;
                list.push(temp);
            }
        }

        //step7:审核人 选择器
        ,approvePicker : function () {
            var that = this;

            var data1 = that.params.data1;
            var picker1El = document.getElementById('picker1');
            var picker1 = new Picker({
                data: [data1]
            });
            //选择后调用
            picker1.on('picker.select', function(selectedVal, selectedIndex) {
              if ($.inArray(selectedVal.toString(),that.params.ids) != -1) {
                $alert(data1[selectedIndex[0]].text+'  已经存在，请重新选择');
                return false;
              }
                //选择出行人
                var interText = doT.template($("#person_tpl").text());
                $(".expense_person").append(interText({
                    'text': data1[selectedIndex[0]].text,
                    'val': selectedVal
                }));
                // data1.splice(selectedIndex[0], 1);
                that.params.ids.push(selectedVal.toString());
            });
            //添加触发
            picker1El.addEventListener('click', function() {
                picker1.show(function() {
                    picker1.refill([data1]);
                });
            });
        }

        //step8:删除审批人员
        ,delTravelPersonAddEvent: function () {
            var that = this;
            $('body').on('click', '.del_travel_person', function () {
                var temp = [];
                temp.value = $(this).parent().attr('data-val');
                temp.text = $(this).parent().find('.u_name').text();
                // that.params.data1.push(temp);
                that.params.ids.splice($.inArray(temp.value,that.params.ids),1);
                $(this).parent().remove();
            });
        }

        //step9：选择器	申请单
        ,initPickerApply : function () {
            var that = this;


            var data2 = that.params.data2;
            //step2:点击事件
            var picker2El = document.getElementById('picker2');
            var picker2 = new Picker({
                data: [data2]
            });
            //选择后调用
            picker2.on('picker.select', function(selectedVal, selectedIndex) {
                $("#order_list").text('');
                $("#picker2").find('span').text(data2[selectedIndex[0]].text);
                that.getOrderList(1, data2[selectedIndex[0]].text);
            });
            //添加触发
            picker2El.addEventListener('click', function() {
                if (data2.length > 0) {
                    picker2.show();
                } else {
                    toast.custom({
                        title: "还没有申请单",
                        html: '<i class="aui-iconfont aui-icon-info"></i>',
                        duration: 2000
                    });
                }
            });
        }

        //step10:发送监听事件
        ,addOrderChooseIds: function () {
            var that = this;

            api.addEventListener({
                name: 'order_choose_ids'
            }, function(ret, err) {
                that.getOrderList(2, ret.value.orderids);
            });
        }

        //step11:开始日期和结束日期点击
        ,startEndDateClick : function () {
            var that = this;

            $('#my-endDate,#my-startDate').click(function(e) {
                var _this = $(this);
                var time = that.getNowFormatDate();
                var minDate = time;
                var stratTime = $('#my-startDate').val();
                if (_this.val()) time = _this.val();
                if (_this.attr('id') === 'my-endDate' && stratTime) minDate = stratTime;
                api.openPicker({
                    type: 'date',
                    date: time,
                    minDate: minDate,
                    title: '选择时间'
                }, function(ret, err) {
                    ret.month = ret.month < 10 ? "0" + ret.month : ret.month;
                    ret.day   = ret.day < 10 ? "0" + ret.day : ret.day;
                    if (_this.attr('id') === 'my-endDate') {
                        if (!stratTime) {
                            $toast('请先选择开始日期!');
                            return false;
                        }
                        if (that.compareDate(ret.year + "-" + ret.month + "-" + ret.day, stratTime)) {
                            $toast('出差结束日期需大于出发日期!');
                            return false;
                        }
                    } else{
                        $('#my-endDate').val('');
                    }
                    if (api.systemType !== 'ios') {
                        if (that.compareDate(ret.year + "-" + ret.month + "-" + ret.day, minDate)) {
                            $toast('请选择正确时间!');
                            return false;
                        }
                    }
                    _this.val(ret.year + "-" + ret.month + "-" + ret.day);
                });
            });
        }

        //step12:添加报销单明细
        ,addExpendseClick : function () {
            var that = this;

            $(".add_expendse").click(function() {
                var interText = doT.template($("#expendse_tpl").text());
                var expendse_index = $(".revocation").length + 1;
                $(this).before(interText(expendse_index));
                //删除报销单明细
                $(".tag-del").click(function() {
                    $(this).parent().parent().parent().next().remove();
                    $(this).parent().parent().parent().next().remove();
                    $(this).parent().parent().parent().next().remove();
                    $(this).parent().parent().parent().remove();
                    //重新排序
                    $(".detail-sort").each(function(i) {
                        $(this).text('(' + (i + 2) + ')');
                    });
                });
            });
        }

        //step13:计算日期
        ,calculateDate : function () {
            var that = this;

            var start_time = '';
            var end_time = '';
            $("#order_list input[name='travel_start_time']").each(function() {
                if (start_time === '') {
                    start_time = $(this).val();
                } else {
                    if (start_time > $(this).val()) {
                        start_time = $(this).val();
                    }
                }
            });
            $("#order_list input[name='travel_end_time']").each(function() {
                if (end_time === '') {
                    end_time = $(this).val();
                } else {
                    if (end_time < $(this).val()) {
                        end_time = $(this).val();
                    }
                }
            });
            var date1 = new Date(start_time * 1000);
            var Y1 = date1.getFullYear() + '-';
            var M1 = (date1.getMonth() + 1 < 10 ? '0' + (date1.getMonth() + 1) : date1.getMonth() + 1) + '-';
            var D1 = date1.getDate() + ' ';
            var date2 = new Date(end_time * 1000);
            var Y2 = date2.getFullYear() + '-';
            var M2 = (date2.getMonth() + 1 < 10 ? '0' + (date2.getMonth() + 1) : date2.getMonth() + 1) + '-';
            var D2 = date2.getDate() + ' ';

            $("#my-startDate").val(Y1 + M1 + D1);
            $("#my-endDate").val(Y2 + M2 + D2);

            that.calculatePrice();
        }

        /**
         * step14:计算总金额
         * 注：授信和余额的金额不计算在内
         */
        ,calculatePrice : function () {
            var that = this;

            $('body').on('keyup','.calculate_price', function(){
                //step1:订单列表中计算订单总额
                var order_price = 0; //订单金额
                var priceTemp = 0; //临时金额
                $("#order_list ul").each(function() {
                    //授信和余额的金额不计算在内
                    if ($(this).attr('data-paycode') !== 'credit' && $(this).attr('data-paycode') !== 'balance') {
                        priceTemp = parseFloat($(this).attr('data-price'));
                        order_price += priceTemp;
                    }
                });
                $("#order_price").text(order_price);
                //step2:计算明细总额
                var detail_price = 0;
                var detailTemp = 0;
                $(".detail_price input").each(function() {
                    if ($(this).val() !== '') {
                        detailTemp = parseFloat($(this).val());
                        detail_price += detailTemp;
                    }
                });
                $("#detail_price").text(detail_price);
                //step3:报销总额
                var totalPrice = order_price + detail_price;
                $("#total_price").text(totalPrice);
            })
        }

        //step15:提交出差申请单
        , submitData :function () {
            var that = this;

            //点击提交的操作
            $('#submitData').click(function () {
                //验证器
                if (!that.validateData()) {
                    return false;
                }
                //订单IDS
                var order_ids = '';
                $("#order_list ul").each(function() {
                    order_ids += $(this).attr('data-id') + ',';
                });
                order_ids = order_ids.substr(0, order_ids.length - 1);

                var request_code = $("#picker2 span").text();

                var travel_start_time = $("#my-startDate").val();
                var travel_end_time = $("#my-endDate").val();

                //报销明细
                var detail;
                var detailArr = [];
                $(".detail_price").each(function() {
                    if (parseFloat($(this).find('input').val()) > 0) {
                        var json = {};
                        //金额
                        json.money = $(this).find('input').val();
                        //明细
                        json.particulars = $(this).next().find('textarea').val();
                        //拼接图片数组
                        var img_url = [];
                        if ($(this).next().next().find('div.img-div').length > 0) {
                            $(this).next().next().find('div.img-div').each(function() {
                                //img_str += $(this).find('img').attr('src') + ',';
                                var imgObj = {
                                    'src': $(this).find('img').attr('src')
                                };
                                img_url.push(imgObj);
                            });
                        }
                        json.imgArr = img_url;
                        detailArr.push(json);
                    }
                });
                if (detailArr.length > 0) {
                    detail = detailArr;
                }

                var order_price = $("#order_price").text();
                var detail_price = $("#detail_price").text();
                var total_price = $("#total_price").text();
                //审批人
                var approver = '';
                $(".expense_person li").each(function() {
                    approver += $(this).attr('data-val') + ',';
                });
                approver = approver.substr(0, approver.length - 1);

                var param = {};
                param.url = Config.travel.addExpense;
                param.data = {
                    detail: detail,
                    total_money: total_price,
                    detailed_sum: detail_price,
                    order_money: order_price,
                    request_code: request_code,
                    approver_id: approver,
                    travel_start_time: travel_start_time,
                    travel_end_time: travel_end_time,
                    order_ids: order_ids
                    ,XDEBUG_SESSION_START: 'PHPSTORM'
                };
                //return false;
                ajax(param, function(ret) {
                    if (ret.code === 1) {
                        $alert('申请成功', function() {
                            api.openWin({
                                name: 'travel_expense_order_win',
                                url: './travel_expense_order_win.html',
                                slidBackEnabled: false
                            });
                        });
                    } else {
                        $toast('申请失败');
                    }
                })
            });

        }

        //step16:验证数据有效性
        ,validateData: function () {
            var that = this;

            //明细
            $(".detail_price").each(function() {
                //金额
                if ($(this).find('input').val() !== '') {
                    var test_money = /^\d+\.?\d{0,2}$/;
                    if (!test_money.test($(this).find('input').val())) {
                        toast.custom({
                            title: "金额不正确",
                            html: '<i class="aui-iconfont aui-icon-info"></i>',
                            duration: 2000
                        });
                        return false;
                    }
                    //详情
                    if ($(this).next().find('textarea').val() === '') {
                        toast.custom({
                            title: "请填写费用明细",
                            html: '<i class="aui-iconfont aui-icon-info"></i>',
                            duration: 2000
                        });
                        return false;
                    }
                    //图片
                    if ($(this).next().next().find('div.img-div').length === 0) {
                        toast.custom({
                            title: "请上传图片凭据",
                            html: '<i class="aui-iconfont aui-icon-info"></i>',
                            duration: 2000
                        });
                        return false;
                    }
                }
            });
            var total_price = parseFloat($("#total_price").text());
            if (total_price <= 0) {
                toast.custom({
                    title: "无报销金额",
                    html: '<i class="aui-iconfont aui-icon-info"></i>',
                    duration: 2000
                });
                return false;
            }
            //审批人
            if ($(".expense_person li").length === 0) {
                toast.custom({
                    title: "请选择审批人",
                    html: '<i class="aui-iconfont aui-icon-info"></i>',
                    duration: 2000
                });
                return false;
            }
            return true;
        }

        //step17:上传图片
        ,uploadImg :function () {
            var that = this;

            $('body').on('change', '.upload_img', function () {
                var self = $(this);
                var img_num = self.parent().siblings('.img-div').find('img').length;
                if (img_num >= 5) {
                    toast.custom({
                        title: "最多五张图片",
                        html: '<i class="aui-iconfont aui-icon-info"></i>',
                        duration: 2000
                    });
                    return false;
                }
                var file = self[0].files[0];
                // 验证文件类型
                var mime = file.type;
                var allow_type = ['image/jpeg', 'image/gif', 'image/png', 'image/bmp'];
                if (allow_type.indexOf(mime) === -1) {
                    alert("请确保文件为图像类型");
                    return false;
                }
                // 图片预览
                var reader = new FileReader();

                reader.readAsDataURL(file);
                reader.onload = function() {
                    var interText = doT.template($("#img_tpl").text());
                    self.parent().after(interText(reader.result));
                    var img = new Image();
                    img.src = reader.result.toString();
                    img.onload = function() {
                        //压缩图片
                        var square = 500;
                        var canvas = document.createElement('canvas');
                        canvas.width = square;
                        canvas.height = square;
                        var context = canvas.getContext('2d');
                        context.clearRect(0, 0, square, square);
                        var imageWidth;
                        var imageHeight;
                        var offsetX = 0;
                        var offsetY = 0;
                        //获取图片的宽高
                        if (img.width > img.height) {
                            imageWidth = Math.round(square * img.width / img.height);
                            imageHeight = square;
                            offsetX = -Math.round((imageWidth - square) / 2);
                        } else {
                            imageHeight = Math.round(square * img.height / img.width);
                            imageWidth = square;
                            offsetY = -Math.round((imageHeight - square) / 2);
                        }
                        context.drawImage(img, offsetX, offsetY, imageWidth, imageHeight);
                        var imgData = canvas.toDataURL('image/jpeg');
                        var param = {};
                        param.url = Config.travel.uploadImg;
                        param.data = {
                            imgData: imgData
                        };
                        ajax(param, function(ret) {
                            if (ret.code === 1) {
                                self.parent().next().find('img').attr('src', ret.data.url_path);
                            } else {
                                toast.custom({
                                    title: ret.msg,
                                    html: '<i class="aui-iconfont aui-icon-info"></i>',
                                    duration: 2000
                                });
                                self.parent().prev().remove();
                            }
                        })
                    };
                }
            });
        }

        //step18:显示订单
        ,showOrder :function () {
            $('body').on('click', '.show_order', function() {
                //折叠
                $('.order_' + $(this).attr('data-group')).toggle();
                //文字显示
                var i = $(this).text();
                if (i === '展开') {
                    $(this).empty().text('收回');
                } else if(i === '收回'){
                    $(this).empty().text('展开');
                }
            });
        }

        //获取当前时间，格式YYYY-MM-DD
        ,getNowFormatDate: function () {
            var date = new Date();
            var seperator1 = "-";
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            return year + seperator1 + month + seperator1 + strDate;
        }
        // 比较时间，格式YYYY-MM-DD
        ,compareDate: function  (d1,d2) {
            let arrayD1 = d1.split("-");
            let date1 = new Date(arrayD1[0],arrayD1[1],arrayD1[2]);
            let arrayD2 = d2.split("-");
            let date2 = new Date(arrayD2[0],arrayD2[1],arrayD2[2]);
            //8/26 8/27
            if(date1 >= date2){
                return false;
            }
            return true;
        }
        //step18:图片删除操作
        ,imageDelete: function () {
            $('body').on('click', '.delete', function () {
                $(this).parent().parent().remove();
            });
        }
    };
    window.expenseAdd =  expenseAdd;
})(window);
